package wx

import (
	"fmt"
	"github.com/thedevsaddam/gojsonq/v2"
	"io/ioutil"
	"net/http"
	"project/pkg/models"
	"project/pkg/setting"
	"project/pkg/validate"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
)

const (
	code2sessionURL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code"
)

func (h *WHandler) WxGetOpenID(c *gin.Context) {
	resp := new(models.RespData)
	req := new(models.WxOpenIdReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("wx:WxGetOpenID with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("wx:WxGetOpenID with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//调用auth.code2Session接口获取openid
	url := fmt.Sprintf(code2sessionURL, setting.Conf.AppID, setting.Conf.Secret, req.JsCode)
	response, err := http.Get(url)
	if err != nil {
		fmt.Println("请求错误", err)
		return
	}
	defer response.Body.Close()
	body, err := ioutil.ReadAll(response.Body)
	if err != nil {
		zap.L().Error("openid is failed", zap.Error(err))
		return
	}
	json1 := gojsonq.New().FromString(string(body)).Find("openid")
	json2 := gojsonq.New().FromString(string(body)).Find("session_key")
	openId := json1.(string)
	sessionKey := json2.(string)
	fmt.Println("my openid is: ", openId)
	re := &models.WxOpenIdResp{
		OpenID:     openId,
		SessionKey: sessionKey,
	}
	resp.Data = re
	resp.SendSuccess(c)
}
